# Contributor: Sören Tempel <soeren+alpine@soeren-tempel.net>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>
pkgname=ca-certificates
pkgver=20230506
pkgrel=0
pkgdesc="Common CA certificates PEM files from Mozilla"
url="https://www.mozilla.org/en-US/about/governance/policies/security-group/certs/"
arch="all"
# There is a GPL-2.0-or-later script inside the source but it is not shipped
license="MPL-2.0 AND MIT"
makedepends_build="perl"
makedepends_host="openssl-dev>3"
subpackages="$pkgname-doc $pkgname-bundle"
replaces="openssl"
options="!fhs !check"
triggers="ca-certificates.trigger=/usr/share/ca-certificates:/usr/local/share/ca-certificates:/etc/ssl/certs:/etc/ca-certificates/update.d"
install="$pkgname.post-deinstall"
source="https://gitlab.alpinelinux.org/alpine/ca-certificates/-/archive/$pkgver/ca-certificates-$pkgver.tar.bz2"

build() {
	make
}

package() {
	make install DESTDIR="$pkgdir"

	(
		echo "# Automatically generated by $pkgname-$pkgver-$pkgrel"
		echo "# $(date -u)"
		echo "#"
		cd "$pkgdir"/usr/share/ca-certificates
		find . -name '*.crt' | sort | cut -b3-
	) > "$pkgdir"/etc/ca-certificates.conf

	# generate the bundle in similar way as update-ca-certificates would do
	for i in $(ls *.crt | sort); do
		cat "$i"
		printf "\n"
	done > "$pkgdir"/etc/ssl/certs/ca-certificates.crt

	mkdir -p "$pkgdir"/etc/apk/protected_paths.d
	cat > "$pkgdir"/etc/apk/protected_paths.d/ca-certificates.list <<-EOF
		-etc/ssl/certs/ca-certificates.crt
		-etc/ssl/certs/ca-cert-*.pem
		-etc/ssl/certs/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].[r0-9]*
	EOF

	cat > "$pkgdir"/etc/ca-certificates/update.d/certhash <<-EOF
		#!/bin/sh
		exec /usr/bin/c_rehash /etc/ssl/certs
	EOF
	chmod +x "$pkgdir"/etc/ca-certificates/update.d/certhash
}

bundle() {
	pkgdesc="Pre generated bundle of Mozilla certificates"
	replaces="libressl2.7-libcrypto libcrypto1.1"
	provides="$pkgname-cacert=$pkgver-r$pkgrel"
	mkdir -p "$subpkgdir"/etc/ssl/certs
	mv "$pkgdir"/etc/ssl/certs/ca-certificates.crt \
		"$subpkgdir"/etc/ssl/certs/
	ln -s certs/ca-certificates.crt \
		"$subpkgdir"/etc/ssl/cert.pem

	# Symlinks for OpenSSL 1.1 compatibility
	mkdir -p "$subpkgdir"/etc/ssl1.1/
	ln -s /etc/ssl/certs "$subpkgdir"/etc/ssl1.1/
	ln -s /etc/ssl/cert.pem "$subpkgdir"/etc/ssl1.1/
}

sha512sums="
cb1941393b0e91cecb4febd149132fbd2ac2a663d07eb8b1333b1ce297b542718aeeb773dbdbdbe72425ec76c045d390ddd1e9ffa0d0d390311f549b1465f652  ca-certificates-20230506.tar.bz2
"
